# 头条自动化服务 - 增强版（带详细日志）
import time
import json
import os
import logging
import traceback
import qrcode
from io import BytesIO
import base64
from datetime import datetime
from DrissionPage import ChromiumPage, ChromiumOptions
from typing import Dict, Optional, List
from config import Config
from database import Database

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('toutiao_service.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)

class ToutiaoService:
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.logger.info("=" * 50)
        self.logger.info("🚀 头条自动化服务初始化开始")
        
        try:
            self.db = Database()
            self.page = None
            self.is_logged_in = False
            self.logger.info("✅ 头条自动化服务初始化完成")
        except Exception as e:
            self.logger.error(f"❌ 头条自动化服务初始化失败: {str(e)}")
            self.logger.error(f"详细错误: {traceback.format_exc()}")
            raise
        
    def init_browser(self):
        """初始化浏览器"""
        self.logger.info("🌐 开始初始化浏览器")
        
        try:
            # 配置浏览器选项
            self.logger.info("⚙️ 配置浏览器选项")
            options = ChromiumOptions()
            
            # 设置无头模式
            if Config.BROWSER_HEADLESS:
                self.logger.info("🔲 启用无头模式")
                options.set_argument('--headless')
            else:
                self.logger.info("🖥️ 使用有界面模式")
            
            # 设置用户数据目录
            user_data_dir = './browser_data'
            self.logger.info(f"📁 设置用户数据目录: {user_data_dir}")
            options.set_argument(f'--user-data-dir={user_data_dir}')
            
            # 确保目录存在
            os.makedirs(user_data_dir, exist_ok=True)
            
            # 其他浏览器设置
            browser_args = [
                '--no-sandbox',
                '--disable-dev-shm-usage',
                '--disable-gpu',
                '--window-size=1920,1080',
                '--disable-web-security',
                '--disable-features=VizDisplayCompositor'
            ]
            
            for arg in browser_args:
                self.logger.debug(f"🔧 添加浏览器参数: {arg}")
                options.set_argument(arg)
            
            # 创建浏览器实例
            self.logger.info("🚀 创建ChromiumPage实例")
            self.page = ChromiumPage(options)
            
            # 验证浏览器是否成功启动
            if self.page:
                self.logger.info("✅ 浏览器初始化成功")
                return True
            else:
                self.logger.error("❌ 浏览器初始化失败: page对象为None")
                return False
            
        except Exception as e:
            self.logger.error(f"❌ 初始化浏览器失败: {str(e)}")
            self.logger.error(f"详细错误: {traceback.format_exc()}")
            return False
    
    def generate_login_qr(self) -> Optional[str]:
        """生成登录二维码"""
        self.logger.info("📱 开始生成登录二维码")
        
        try:
            # 检查浏览器是否已初始化
            if not self.page:
                self.logger.warning("⚠️ 浏览器未初始化，尝试初始化")
                if not self.init_browser():
                    self.logger.error("❌ 浏览器初始化失败，无法生成二维码")
                    return None
            
            # 访问头条登录页面
            login_url = Config.TOUTIAO_LOGIN_URL
            self.logger.info(f"🌐 访问头条登录页面: {login_url}")
            self.page.get(login_url)
            
            self.logger.info("⏳ 等待页面加载（3秒）")
            time.sleep(3)
            
            # 首先检查是否已经登录
            current_url = self.page.url
            self.logger.info(f"🌐 当前页面URL: {current_url}")
            
            if 'mp.toutiao.com' in current_url and 'login' not in current_url:
                self.logger.info("✅ 检测到已登录状态，无需二维码")
                self.is_logged_in = True
                
                # 获取并保存用户信息
                self.logger.info("🔍 获取用户信息并保存到数据库")
                try:
                    user_info = self._get_user_info()
                    if user_info:
                        # 保存用户信息到数据库
                        cookies = self.page.cookies()
                        cookie_str = json.dumps(cookies)
                        
                        account_id = self.db.save_account(
                            username=user_info.get('username', ''),
                            nickname=user_info.get('nickname', ''),
                            avatar_url=user_info.get('avatar_url', ''),
                            cookies=cookie_str
                        )
                        
                        self.logger.info(f"💾 账号信息保存成功，ID: {account_id}")
                    else:
                        self.logger.warning("⚠️ 获取用户信息失败")
                except Exception as save_e:
                    self.logger.error(f"❌ 保存用户信息失败: {str(save_e)}")
                
                return "ALREADY_LOGGED_IN"  # 特殊返回值表示已登录
            
            # 查找二维码登录选项
            self.logger.info("🔍 查找二维码登录选项")
            qr_selectors = [
                '@data-track-click=login_qrcode_tab',
                '.login-qrcode-tab',
                '[data-track-click="login_qrcode_tab"]',
                'text:二维码登录'
            ]
            
            qr_tab = None
            for selector in qr_selectors:
                self.logger.debug(f"🔍 尝试选择器: {selector}")
                qr_tab = self.page.ele(selector, timeout=5)
                if qr_tab:
                    self.logger.info(f"✅ 找到二维码登录选项: {selector}")
                    break
            
            if qr_tab:
                self.logger.info("👆 点击二维码登录选项")
                qr_tab.click()
                time.sleep(2)  # 等待二维码加载
            else:
                self.logger.warning("⚠️ 未找到二维码登录选项，继续尝试获取二维码")
            
            # 获取二维码图片
            self.logger.info("🔍 查找二维码图片")
            qr_selectors = [
                'x://*[@id="BD_Login_Form"]/div/article/article/div[1]/div[2]/article/div/div/img',
                'tag:img@@src^=data:image',
                '.qrcode img',
                '#qrcode img',
                'img[src*="qr"]',
                'img[alt*="二维码"]'
            ]
            
            qr_img = None
            for selector in qr_selectors:
                self.logger.debug(f"🔍 尝试二维码选择器: {selector}")
                qr_img = self.page.ele(selector, timeout=5)
                if qr_img:
                    self.logger.info(f"✅ 找到二维码图片: {selector}")
                    break
            
            if qr_img:
                qr_src = qr_img.attr('src')
                if qr_src:
                    self.logger.info("✅ 成功获取二维码图片URL")
                    self.logger.debug(f"🔗 二维码URL长度: {len(qr_src)} 字符")
                    return qr_src
                else:
                    self.logger.warning("⚠️ 二维码图片src属性为空")
            
            # 如果没有找到二维码图片，尝试canvas
            self.logger.info("🔍 尝试查找canvas二维码")
            qr_canvas = self.page.ele('tag:canvas', timeout=5)
            if qr_canvas:
                self.logger.info("✅ 找到canvas二维码，尝试转换")
                try:
                    qr_data = self.page.run_js('''
                        var canvas = arguments[0];
                        if (canvas && canvas.toDataURL) {
                            return canvas.toDataURL();
                        }
                        return null;
                    ''', qr_canvas)
                    
                    if qr_data:
                        self.logger.info("✅ 成功从canvas获取二维码")
                        return qr_data
                    else:
                        self.logger.warning("⚠️ canvas转换失败")
                except Exception as canvas_e:
                    self.logger.error(f"❌ canvas转换出错: {str(canvas_e)}")
            
            # 如果没有找到二维码，可能已经登录了
            self.logger.info("🔍 未找到二维码，再次检查登录状态")
            current_url = self.page.url
            if 'mp.toutiao.com' in current_url and 'login' not in current_url:
                self.logger.info("✅ 检测到已登录状态")
                self.is_logged_in = True
                
                # 获取并保存用户信息
                self.logger.info("🔍 获取用户信息并保存到数据库")
                try:
                    user_info = self._get_user_info()
                    if user_info:
                        # 保存用户信息到数据库
                        cookies = self.page.cookies()
                        cookie_str = json.dumps(cookies)
                        
                        account_id = self.db.save_account(
                            username=user_info.get('username', ''),
                            nickname=user_info.get('nickname', ''),
                            avatar_url=user_info.get('avatar_url', ''),
                            cookies=cookie_str
                        )
                        
                        self.logger.info(f"💾 账号信息保存成功，ID: {account_id}")
                    else:
                        self.logger.warning("⚠️ 获取用户信息失败")
                except Exception as save_e:
                    self.logger.error(f"❌ 保存用户信息失败: {str(save_e)}")
                
                return "ALREADY_LOGGED_IN"
            
            # 记录当前页面状态
            self.logger.warning(f"⚠️ 未找到二维码，当前页面URL: {current_url}")
            
            # 尝试截图以便调试
            try:
                screenshot_path = f"debug_screenshot_{int(time.time())}.png"
                self.page.get_screenshot(screenshot_path)
                self.logger.info(f"📸 已保存调试截图: {screenshot_path}")
            except Exception as screenshot_e:
                self.logger.warning(f"⚠️ 截图失败: {str(screenshot_e)}")
                
            return None
            
        except Exception as e:
            self.logger.error(f"❌ 生成登录二维码失败: {str(e)}")
            self.logger.error(f"详细错误: {traceback.format_exc()}")
            return None
    
    def check_login_status(self) -> Dict[str, any]:
        """检查登录状态"""
        self.logger.info("🔍 检查登录状态")
        
        try:
            if not self.page:
                self.logger.error("❌ 浏览器未初始化")
                return {"success": False, "message": "浏览器未初始化"}
            
            # 检查当前URL
            current_url = self.page.url
            self.logger.info(f"🌐 当前页面URL: {current_url}")
            
            # 判断是否登录成功
            if 'mp.toutiao.com' in current_url and 'login' not in current_url:
                self.logger.info("🎉 检测到登录成功页面")
                
                # 获取用户信息
                self.logger.info("👤 获取用户信息")
                user_info = self._get_user_info()
                
                if user_info:
                    self.logger.info(f"✅ 用户信息获取成功: {user_info.get('nickname', '未知用户')}")
                    
                    # 保存cookies
                    self.logger.info("🍪 保存登录cookies")
                    try:
                        cookies = self.page.cookies()
                        cookie_str = json.dumps(cookies)
                        self.logger.debug(f"🍪 获取到 {len(cookies)} 个cookies")
                        
                        # 保存到数据库
                        account_id = self.db.save_account(
                            username=user_info.get('username', ''),
                            nickname=user_info.get('nickname', ''),
                            avatar_url=user_info.get('avatar_url', ''),
                            cookies=cookie_str
                        )
                        
                        self.logger.info(f"💾 账号信息保存成功，ID: {account_id}")
                        
                        self.is_logged_in = True
                        return {
                            "success": True,
                            "message": "登录成功",
                            "user_info": user_info,
                            "account_id": account_id
                        }
                    except Exception as cookie_e:
                        self.logger.error(f"❌ 保存cookies失败: {str(cookie_e)}")
                        return {"success": False, "message": f"保存登录信息失败: {str(cookie_e)}"}
                else:
                    self.logger.warning("⚠️ 获取用户信息失败，可能登录未完全成功")
                    return {"success": False, "message": "获取用户信息失败"}
            
            self.logger.debug("⏳ 仍在等待扫码登录")
            return {"success": False, "message": "等待扫码登录"}
            
        except Exception as e:
            self.logger.error(f"❌ 检查登录状态失败: {str(e)}")
            self.logger.error(f"详细错误: {traceback.format_exc()}")
            return {"success": False, "message": f"检查登录状态失败: {str(e)}"}
    
    def _get_user_info(self) -> Optional[Dict]:
        """获取用户信息"""
        self.logger.info("👤 开始获取用户信息")
        
        try:
            user_info = {}
            
            # 访问用户资料页面获取准确的用户信息
            self.logger.info("🌐 访问用户资料页面获取用户信息")
            profile_url = "https://mp.toutiao.com/profile_v4/index"
            
            try:
                self.page.get(profile_url)
                time.sleep(3)  # 等待页面加载
                self.logger.info("✅ 用户资料页面加载完成")
                
                # 获取用户名
                self.logger.info("🔍 开始提取用户名")
                username_elem = self.page.ele('x://*[@id="masterRoot"]/div/div[1]/div/div[2]/div[3]/div[1]/a/span/div/div/div[1]', timeout=5)
                if username_elem:
                    username = username_elem.text
                    if username and username.strip():
                        user_info['username'] = username.strip()
                        user_info['nickname'] = username.strip()  # 昵称和用户名相同
                        self.logger.info(f"✅ 成功获取用户名: {username.strip()}")
                    else:
                        self.logger.warning("⚠️ 用户名元素存在但文本为空")
                else:
                    self.logger.warning("⚠️ 未找到用户名元素")
                
                # 获取头像
                self.logger.info("🔍 开始提取头像")
                avatar_elem = self.page.ele('x://*[@id="masterRoot"]/div/div[1]/div/div[2]/div[3]/div[1]/a/span/div/span/img', timeout=3)
                if avatar_elem:
                    avatar_url = avatar_elem.attr('src')
                    if avatar_url:
                        user_info['avatar_url'] = avatar_url
                        self.logger.info("✅ 成功获取头像URL")
                    else:
                        self.logger.warning("⚠️ 头像元素存在但src为空")
                else:
                    self.logger.warning("⚠️ 未找到头像元素")
                        
            except Exception as elem_e:
                self.logger.error(f"❌ 获取用户信息失败: {str(elem_e)}")
                self.logger.error(f"详细错误: {traceback.format_exc()}")
            
            # 设置默认用户名
            if not user_info.get('username'):
                if user_info.get('nickname'):
                    user_info['username'] = user_info['nickname']
                else:
                    user_info['username'] = f'toutiao_user_{int(time.time())}'
                self.logger.info(f"📝 设置默认用户名: {user_info['username']}")
            
            # 设置默认昵称
            if not user_info.get('nickname'):
                user_info['nickname'] = user_info.get('username', '头条用户')
            
            self.logger.info(f"✅ 用户信息获取完成: {user_info}")
            return user_info
            
        except Exception as e:
            self.logger.error(f"❌ 获取用户信息失败: {str(e)}")
            # 即使失败也返回基本信息
            return {
                'username': f'toutiao_user_{int(time.time())}',
                'nickname': '头条用户'
            }
    
    def restore_login_session(self) -> bool:
        """恢复登录会话"""
        self.logger.info("🔄 开始恢复登录会话")
        
        try:
            # 获取保存的账号信息
            account = self.db.get_active_account()
            if not account:
                self.logger.warning("⚠️ 未找到保存的账号信息")
                return False
            
            if not account.get('cookies'):
                self.logger.warning("⚠️ 账号信息中没有cookies")
                return False
            
            self.logger.info(f"📝 找到账号: {account.get('nickname', '未知用户')}")
            
            # 初始化浏览器
            if not self.page:
                self.logger.info("🌐 浏览器未初始化，开始初始化")
                if not self.init_browser():
                    self.logger.error("❌ 浏览器初始化失败")
                    return False
            
            # 访问头条主页
            self.logger.info("🌐 访问头条主页")
            self.page.get('https://mp.toutiao.com')
            time.sleep(2)
            
            # 恢复cookies
            self.logger.info("🍪 开始恢复cookies")
            try:
                cookies = json.loads(account['cookies'])
                self.logger.debug(f"🍪 准备恢复 {len(cookies)} 个cookies")
                
                success_count = 0
                for i, cookie in enumerate(cookies):
                    try:
                        self.page.set.cookies(cookie)
                        success_count += 1
                        self.logger.debug(f"✅ Cookie {i+1}/{len(cookies)} 恢复成功")
                    except Exception as cookie_e:
                        self.logger.warning(f"⚠️ Cookie {i+1} 恢复失败: {str(cookie_e)}")
                        continue
                
                self.logger.info(f"🍪 Cookies恢复完成: {success_count}/{len(cookies)} 成功")
                
            except json.JSONDecodeError as json_e:
                self.logger.error(f"❌ Cookies JSON解析失败: {str(json_e)}")
                return False
            
            # 刷新页面验证登录状态
            self.logger.info("🔄 刷新页面验证登录状态")
            self.page.refresh()
            self.logger.info("⏳ 等待页面加载（3秒）")
            time.sleep(3)
            
            # 检查登录状态
            current_url = self.page.url
            self.logger.info(f"🌐 当前页面URL: {current_url}")
            
            if 'mp.toutiao.com' in current_url and 'login' not in current_url:
                self.logger.info("✅ 登录会话恢复成功")
                self.is_logged_in = True
                return True
            else:
                self.logger.warning("⚠️ 登录会话恢复失败，可能需要重新登录")
                return False
            
        except Exception as e:
            self.logger.error(f"❌ 恢复登录会话失败: {str(e)}")
            self.logger.error(f"详细错误: {traceback.format_exc()}")
            return False
    
    def publish_article(self, title: str, content: str, cover_image_path: str = None) -> Dict[str, any]:
        """发布文章"""
        self.logger.info("📝 开始发布文章")
        self.logger.info(f"📋 文章标题: {title[:50]}{'...' if len(title) > 50 else ''}")
        self.logger.info(f"📄 文章内容长度: {len(content)} 字符")
        
        try:
            # 检查登录状态
            if not self.is_logged_in:
                self.logger.warning("⚠️ 用户未登录，尝试恢复登录会话")
                if not self.restore_login_session():
                    self.logger.error("❌ 用户未登录且会话恢复失败")
                    return {"success": False, "message": "用户未登录"}
            
            # 访问发布页面
            publish_url = Config.TOUTIAO_PUBLISH_URL
            self.logger.info(f"🌐 访问发布页面: {publish_url}")
            self.page.get(publish_url)
            self.logger.info("⏳ 等待发布页面加载（3秒）")
            time.sleep(3)
            
            # 填写标题
            self.logger.info("✏️ 开始填写文章标题")
            title_selectors = [
                #css选择器
                'css:#root > div > div.left-column > div > div.publish-editor > div.publish-editor-title-wrapper > div > div > div.title-wrapper > div > div > div > textarea',
                #xpath选择器
                'x://*[@id="root"]/div/div[1]/div/div[1]/div[3]/div/div/div[2]/div/div/div/textarea',
            ]
            
            title_input = None
            for selector in title_selectors:
                self.logger.debug(f"🔍 尝试标题选择器: {selector}")
                title_input = self.page.ele(selector, timeout=5)
                if title_input:
                    self.logger.info(f"✅ 找到标题输入框: {selector}")
                    break
            
            if title_input:
                try:
                    self.logger.info("🗑️ 清空标题输入框")
                    title_input.clear()
                    self.logger.info("✏️ 输入文章标题")
                    title_input.input(title)
                    self.logger.info("⏳ 等待标题输入完成（1秒）")
                    time.sleep(1)
                    self.logger.info("✅ 标题填写完成")
                except Exception as title_e:
                    self.logger.error(f"❌ 标题输入失败: {str(title_e)}")
                    return {"success": False, "message": f"标题输入失败: {str(title_e)}"}
            else:
                self.logger.error("❌ 找不到标题输入框")
                return {"success": False, "message": "找不到标题输入框"}
            
            # 填写内容
            self.logger.info("✏️ 开始填写文章内容")
            content_selectors = [
                'x://*[@id="root"]/div/div[1]/div/div[1]/div[4]/div/div[1]',
                'css:#root > div > div.left-column > div > div.publish-editor > div.syl-editor-wrap > div > div.ProseMirror'
            ]
            
            content_editor = None
            for selector in content_selectors:
                self.logger.debug(f"🔍 尝试内容选择器: {selector}")
                content_editor = self.page.ele(selector, timeout=5)
                if content_editor:
                    self.logger.info(f"✅ 找到内容编辑器: {content_editor}")
                    break
            
            if content_editor:
                try:
                    self.logger.info("🗑️ 清空内容编辑器")
                    content_editor.clear()
                    self.logger.info("✏️ 输入文章内容")
                    content_editor.input(content)
                    self.logger.info("⏳ 等待内容输入完成（2秒）")
                    time.sleep(2)
                    self.logger.info("✅ 内容填写完成")
                except Exception as content_e:
                    self.logger.error(f"❌ 内容输入失败: {str(content_e)}")
                    return {"success": False, "message": f"内容输入失败: {str(content_e)}"}
            else:
                self.logger.error("❌ 找不到内容编辑器")
                return {"success": False, "message": "找不到内容编辑器"}
            
            # 上传封面图片（必需步骤）
            if not cover_image_path:
                self.logger.error("❌ 封面图片是必需的，无法发布")
                return {"success": False, "message": "封面图片是必需的，请先上传封面图片"}
            
            self.logger.info(f"🖼️ 开始上传封面图片: {cover_image_path}")
            if not self._upload_cover_image(cover_image_path):
                self.logger.error("❌ 封面图片上传失败，无法继续发布")
                return {"success": False, "message": "封面图片上传失败，无法发布文章"}
            
            # 开始发布流程
            self.logger.info("🚀 开始发布文章")
            
            # 步骤1: 点击"发布并预览"按钮
            self.logger.info("📋 步骤1: 点击发布并预览按钮")
            preview_btn_xpath = 'x://*[@id="root"]/div/div[1]/div/div[3]/div/button[3]'
            preview_btn = self.page.ele(preview_btn_xpath, timeout=10)
            
            if not preview_btn:
                self.logger.error("❌ 找不到发布并预览按钮")
                return {"success": False, "message": "找不到发布并预览按钮"}
            
            try:
                self.logger.info("👆 点击发布并预览按钮")
                preview_btn.click()
                self.logger.info("⏳ 等待预览页面加载（3秒）")
                time.sleep(3)
            except Exception as preview_e:
                self.logger.error(f"❌ 点击发布并预览按钮失败: {str(preview_e)}")
                return {"success": False, "message": f"点击发布并预览按钮失败: {str(preview_e)}"}
            
            # 步骤2: 点击"确认发布"按钮
            self.logger.info("✅ 步骤2: 点击确认发布按钮")
            confirm_btn_xpath = 'x://*[@id="root"]/div/div[1]/div/div[3]/div/button[2]'
            confirm_btn = self.page.ele(confirm_btn_xpath, timeout=10)
            
            if not confirm_btn:
                self.logger.error("❌ 找不到确认发布按钮")
                return {"success": False, "message": "找不到确认发布按钮"}
            
            try:
                self.logger.info("👆 点击确认发布按钮")
                confirm_btn.click()
                self.logger.info("⏳ 等待发布处理（5秒）")
                time.sleep(5)
            except Exception as confirm_e:
                self.logger.error(f"❌ 点击确认发布按钮失败: {str(confirm_e)}")
                return {"success": False, "message": f"点击确认发布按钮失败: {str(confirm_e)}"}
            
            # 步骤3: 检查发布结果
            self.logger.info("🔍 检查发布结果")
            success_selectors = [
                ':contains("发布成功")',
                ':contains("发表成功")',
                '.success-message',
                '.publish-success',
                ':contains("已发布")'
            ]
            
            success_indicator = None
            for selector in success_selectors:
                success_indicator = self.page.ele(selector, timeout=10)
                if success_indicator:
                    self.logger.info(f"✅ 发布成功标识: {selector}")
                    break
            
            # 获取当前页面URL作为文章URL
            article_url = self.page.url
            self.logger.info(f"📄 当前页面URL: {article_url}")
            
            if success_indicator or 'mp.toutiao.com' in article_url:
                self.logger.info(f"🎉 文章发布成功! URL: {article_url}")
                return {
                    "success": True,
                    "message": "文章发布成功",
                    "article_url": article_url
                }
            else:
                self.logger.warning("⚠️ 发布结果不确定，请手动检查")
                return {
                    "success": True,  # 假设成功，因为已经完成了发布流程
                    "message": "发布流程已完成，请手动检查结果",
                    "article_url": article_url
                }
                
        except Exception as e:
            self.logger.error(f"❌ 发布文章失败: {str(e)}")
            self.logger.error(f"详细错误: {traceback.format_exc()}")
            return {"success": False, "message": f"发布文章失败: {str(e)}"}
    
    def _upload_cover_image(self, image_path: str) -> bool:
        """上传封面图片"""
        self.logger.info(f"🖼️ 开始上传封面图片: {image_path}")
        
        try:
            # 检查图片文件是否存在
            if not os.path.exists(image_path):
                self.logger.error(f"❌ 图片文件不存在: {image_path}")
                return False
            
            # 步骤1: 点击选择图片的区域
            self.logger.info("👆 点击选择图片区域")
            select_image_xpath = 'x://*[@id="root"]/div/div[1]/div/div[2]/div[2]/div[1]/div/div[2]/div/div[2]/div[1]/div/div/div/div'
            select_image_btn = self.page.ele(select_image_xpath, timeout=10)
            self.page.ele(select_image_xpath).click()
            
            if not select_image_btn:
                self.logger.error("❌ 找不到选择图片区域")
                return False
            
            try:
                select_image_btn.click()
                self.logger.info("⏳ 等待图片选择对话框打开（2秒）")
                time.sleep(2)
            except Exception as click_e:
                self.logger.error(f"❌ 点击选择图片区域失败: {str(click_e)}")
                return False
            
            # 步骤2: 找到并操作本地上传的input元素
            self.logger.info("📁 寻找本地上传input元素")
            upload_input_xpath = 'x:/html/body/div[19]/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div/div/div/div[1]/div/button[1]/div/input'
            upload_input = self.page.ele(upload_input_xpath, timeout=10)
            self.page.ele('x:/html/body/div[19]/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div/div/div/div[1]/div/button[1]/div/input').click()
            
            if not upload_input:
                self.logger.error("❌ 找不到本地上传input元素")
                # 尝试查找页面上所有的input[type=file]元素
                self.logger.info("🔍 尝试查找页面上的文件上传元素")
                file_inputs = self.page.eles('tag:input@@type=file', timeout=5)
                if file_inputs:
                    self.logger.info(f"📋 找到 {len(file_inputs)} 个文件上传元素")
                    upload_input = file_inputs[0]  # 使用第一个找到的
                else:
                    self.logger.error("❌ 页面上找不到任何文件上传元素")
                    return False
            
            try:
                # 使用绝对路径确保文件路径正确
                abs_image_path = os.path.abspath(image_path)
                self.logger.info(f"📤 上传图片文件: {abs_image_path}")
                
                # 直接向input元素设置文件路径
                upload_input.input(abs_image_path)
                self.logger.info("⏳ 等待图片上传处理（5秒）")
                time.sleep(5)
                
                # 检查是否上传成功（可以通过检查页面变化来判断）
                self.logger.info("🔍 检查图片是否上传成功")
                
            except Exception as upload_e:
                self.logger.error(f"❌ 上传图片失败: {str(upload_e)}")
                self.logger.error(f"详细错误: {traceback.format_exc()}")
                return False
            
            # 步骤3: 点击确认按钮
            self.logger.info("✅ 点击确认按钮")
                                      
            confirm_upload_xpath = 'x:/html/body/div[19]/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div/div/div/div[3]/div[2]/button[2]'
            confirm_upload_btn = self.page.ele(confirm_upload_xpath, timeout=10)
            
            if not confirm_upload_btn:
                self.logger.error("❌ 找不到确认按钮")
                return False
            
            try:
                self.page.ele('x:/html/body/div[19]/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div/div/div/div[3]/div[2]/button[2]').click()
                self.logger.info("⏳ 等待图片处理完成（3秒）")
                time.sleep(3)
                self.logger.info("✅ 封面图片上传成功")
                return True
            except Exception as confirm_e:
                self.logger.error(f"❌ 点击确认按钮失败: {str(confirm_e)}")
                return False
                
        except Exception as e:
            self.logger.error(f"❌ 上传封面图片失败: {str(e)}")
            self.logger.error(f"详细错误: {traceback.format_exc()}")
            return False
    
    def get_article_stats(self, article_url: str) -> Dict[str, int]:
        """获取文章统计数据"""
        self.logger.info(f"📊 开始获取文章统计数据: {article_url}")
        
        try:
            # 检查登录状态
            if not self.is_logged_in:
                self.logger.warning("⚠️ 用户未登录，尝试恢复登录会话")
                if not self.restore_login_session():
                    self.logger.error("❌ 用户未登录且会话恢复失败")
                    return {"views": 0, "likes": 0, "comments": 0}
            
            # 访问文章页面
            self.logger.info(f"🌐 访问文章页面")
            self.page.get(article_url)
            self.logger.info("⏳ 等待页面加载（3秒）")
            time.sleep(3)
            
            stats = {"views": 0, "likes": 0, "comments": 0}
            
            # 获取阅读量
            self.logger.debug("📖 获取阅读量")
            views_selectors = [
                ':contains("阅读")',
                '.views-count',
                '.read-count'
            ]
            
            for selector in views_selectors:
                views_elem = self.page.ele(selector, timeout=3)
                if views_elem:
                    views_text = views_elem.text
                    views_num = self._extract_number(views_text)
                    if views_num is not None:
                        stats["views"] = views_num
                        self.logger.info(f"📖 阅读量: {views_num}")
                        break
            
            # 获取点赞数
            self.logger.debug("👍 获取点赞数")
            likes_selectors = [
                ':contains("点赞")',
                '.likes-count',
                '.like-count'
            ]
            
            for selector in likes_selectors:
                likes_elem = self.page.ele(selector, timeout=3)
                if likes_elem:
                    likes_text = likes_elem.text
                    likes_num = self._extract_number(likes_text)
                    if likes_num is not None:
                        stats["likes"] = likes_num
                        self.logger.info(f"👍 点赞数: {likes_num}")
                        break
            
            # 获取评论数
            self.logger.debug("💬 获取评论数")
            comments_selectors = [
                ':contains("评论")',
                '.comments-count',
                '.comment-count'
            ]
            
            for selector in comments_selectors:
                comments_elem = self.page.ele(selector, timeout=3)
                if comments_elem:
                    comments_text = comments_elem.text
                    comments_num = self._extract_number(comments_text)
                    if comments_num is not None:
                        stats["comments"] = comments_num
                        self.logger.info(f"💬 评论数: {comments_num}")
                        break
            
            self.logger.info(f"📊 统计数据获取完成: {stats}")
            return stats
            
        except Exception as e:
            self.logger.error(f"❌ 获取文章统计失败: {str(e)}")
            self.logger.error(f"详细错误: {traceback.format_exc()}")
            return {"views": 0, "likes": 0, "comments": 0}
    
    def _extract_number(self, text: str) -> Optional[int]:
        """从文本中提取数字"""
        try:
            import re
            numbers = re.findall(r'\d+', text)
            if numbers:
                number = int(numbers[0])
                self.logger.debug(f"🔢 从文本 '{text}' 提取数字: {number}")
                return number
            else:
                self.logger.debug(f"🔢 文本 '{text}' 中未找到数字")
                return None
        except Exception as e:
            self.logger.warning(f"⚠️ 数字提取失败: {str(e)}")
            return None
    
    def close_browser(self):
        """关闭浏览器"""
        self.logger.info("🚪 关闭浏览器")
        try:
            if self.page:
                self.page.quit()
                self.page = None
                self.logger.info("✅ 浏览器关闭成功")
            else:
                self.logger.info("ℹ️ 浏览器已经关闭")
        except Exception as e:
            self.logger.error(f"❌ 关闭浏览器失败: {str(e)}")
        
        self.logger.info("=" * 50)
    
    def reconnect_browser(self) -> Dict[str, any]:
        """重新连接浏览器"""
        self.logger.info("🔄 开始重新连接浏览器")
        
        try:
            # 先关闭现有浏览器连接（如果存在）
            if self.page:
                self.logger.info("🚪 关闭现有浏览器连接")
                try:
                    self.page.quit()
                except:
                    pass  # 忽略关闭时的错误
                self.page = None
            
            # 重置登录状态
            self.is_logged_in = False
            
            # 重新初始化浏览器连接
            self.logger.info("🚀 重新初始化浏览器连接")
            if self.init_browser():
                self.logger.info("✅ 浏览器连接成功")
                
                # 检查是否已经登录
                self.logger.info("🔍 检查登录状态")
                login_status = self.check_existing_login()
                
                if login_status["is_logged_in"]:
                    self.is_logged_in = True
                    return {
                        "success": True,
                        "is_logged_in": True,
                        "message": "浏览器连接成功，检测到已登录状态"
                    }
                else:
                    return {
                        "success": True,
                        "is_logged_in": False,
                        "message": "浏览器连接成功，需要重新登录"
                    }
            else:
                self.logger.error("❌ 浏览器连接失败")
                return {
                    "success": False,
                    "message": "浏览器连接失败，请检查系统环境"
                }
                
        except Exception as e:
            self.logger.error(f"❌ 重新连接浏览器失败: {str(e)}")
            self.logger.error(f"详细错误: {traceback.format_exc()}")
            return {
                "success": False,
                "message": f"重新连接浏览器失败: {str(e)}"
            }
    
    def check_existing_login(self) -> Dict[str, any]:
        """检查是否已经存在登录状态"""
        self.logger.info("🔍 检查现有登录状态")
        
        try:
            if not self.page:
                return {"is_logged_in": False, "message": "浏览器未连接"}
            
            # 访问头条主页检查登录状态
            self.logger.info("🌐 访问头条主页检查登录状态")
            self.page.get('https://mp.toutiao.com')
            time.sleep(3)
            
            current_url = self.page.url
            self.logger.info(f"🌐 当前页面URL: {current_url}")
            
            # 如果URL包含mp.toutiao.com且不包含login，说明已登录
            if 'mp.toutiao.com' in current_url and 'login' not in current_url:
                self.logger.info("✅ 检测到已登录状态")
                
                # 获取用户信息
                user_info = self._get_user_info()
                if user_info:
                    # 保存用户信息到数据库
                    try:
                        cookies = self.page.cookies()
                        cookie_str = json.dumps(cookies)
                        
                        account_id = self.db.save_account(
                            username=user_info.get('username', ''),
                            nickname=user_info.get('nickname', ''),
                            avatar_url=user_info.get('avatar_url', ''),
                            cookies=cookie_str
                        )
                        
                        self.logger.info(f"💾 账号信息更新成功，ID: {account_id}")
                    except Exception as save_e:
                        self.logger.warning(f"⚠️ 保存账号信息失败: {str(save_e)}")
                
                return {
                    "is_logged_in": True,
                    "message": "已检测到登录状态",
                    "user_info": user_info
                }
            else:
                self.logger.info("ℹ️ 未检测到登录状态")
                return {
                    "is_logged_in": False,
                    "message": "未检测到登录状态"
                }
                
        except Exception as e:
            self.logger.error(f"❌ 检查登录状态失败: {str(e)}")
            return {
                "is_logged_in": False,
                "message": f"检查登录状态失败: {str(e)}"
            }
    
    def check_browser_connection(self) -> bool:
        """检查浏览器连接状态"""
        try:
            if not self.page:
                self.logger.debug("浏览器页面对象不存在")
                return False
            
            # 尝试获取当前URL来检测连接
            current_url = self.page.url
            if current_url:
                self.logger.debug(f"浏览器连接正常，当前URL: {current_url}")
                return True
            else:
                self.logger.debug("无法获取当前URL，浏览器可能已断开")
                return False
                
        except Exception as e:
            self.logger.debug(f"浏览器连接检测失败: {str(e)}")
            return False
    
    def get_connection_status(self) -> Dict[str, any]:
        """获取连接和登录状态"""
        try:
            # 检查浏览器连接
            browser_connected = self.check_browser_connection()
            
            if not browser_connected:
                self.is_logged_in = False
                return {
                    "browser_connected": False,
                    "is_logged_in": False,
                    "message": "浏览器连接已断开"
                }
            
            # 如果浏览器连接正常，检查登录状态
            if self.is_logged_in:
                # 验证登录状态是否仍然有效
                try:
                    current_url = self.page.url
                    if 'mp.toutiao.com' in current_url and 'login' not in current_url:
                        return {
                            "browser_connected": True,
                            "is_logged_in": True,
                            "message": "已登录"
                        }
                    else:
                        self.is_logged_in = False
                        return {
                            "browser_connected": True,
                            "is_logged_in": False,
                            "message": "登录状态已失效"
                        }
                except:
                    self.is_logged_in = False
                    return {
                        "browser_connected": True,
                        "is_logged_in": False,
                        "message": "登录状态检测失败"
                    }
            else:
                return {
                    "browser_connected": True,
                    "is_logged_in": False,
                    "message": "未登录"
                }
                
        except Exception as e:
            self.logger.error(f"获取连接状态失败: {str(e)}")
            return {
                "browser_connected": False,
                "is_logged_in": False,
                "message": f"状态检测失败: {str(e)}"
            }
    
    def get_articles_from_website(self) -> List[Dict]:
        """从头条官网获取文章数据"""
        self.logger.info("📊 开始从头条官网获取文章数据")
        
        try:
            # 检查登录状态
            if not self.is_logged_in:
                self.logger.warning("⚠️ 用户未登录，尝试恢复登录会话")
                if not self.restore_login_session():
                    self.logger.error("❌ 用户未登录且会话恢复失败")
                    return []
            
            # 访问文章管理页面
            self.logger.info(f"🌐 访问文章管理页面: {Config.TOUTIAO_TITLE_URL}")
            self.page.get(Config.TOUTIAO_TITLE_URL)
            self.logger.info("⏳ 等待页面加载（3秒）")
            time.sleep(3)
            
            articles_data = []
            
            # 获取文章元素 - 最近的文章
            self.logger.info("🔍 开始提取文章数据")
            
            # 文章标题
            title_elements = self.page.eles('x://*[@id="root"]/div/div[2]/div/div[*]/div/div/div/a')
            # 展现量
            zhanxian_elements = self.page.eles('x://*[@id="root"]/div/div[2]/div/div[*]/div/div/div[3]/ul/li[1]')
            # 阅读量
            yueduliang_elements = self.page.eles('x://*[@id="root"]/div/div[2]/div/div[*]/div/div/div[3]/ul/li[2]')
            # 评论数
            pinglun_elements = self.page.eles('x://*[@id="root"]/div/div[2]/div/div[*]/div/div/div[3]/ul/li[3]')
            # 点赞数
            dianzan_elements = self.page.eles('x://*[@id="root"]/div/div[2]/div/div[*]/div/div/div[3]/ul/li[4]')
            
            # 确保所有列表长度一致
            min_length = min(len(title_elements), len(zhanxian_elements), len(yueduliang_elements), 
                           len(pinglun_elements), len(dianzan_elements))
            
            self.logger.info(f"📋 找到 {min_length} 篇文章")
            
            for i in range(min_length):
                try:
                    # 提取文章数据
                    title = title_elements[i].text.strip() if title_elements[i].text else "未知标题"
                    zhanxian = self._extract_number_from_text(zhanxian_elements[i].text) if zhanxian_elements[i].text else 0
                    yueduliang = self._extract_number_from_text(yueduliang_elements[i].text) if yueduliang_elements[i].text else 0
                    pinglun = self._extract_number_from_text(pinglun_elements[i].text) if pinglun_elements[i].text else 0
                    dianzan = self._extract_number_from_text(dianzan_elements[i].text) if dianzan_elements[i].text else 0
                    
                    # 获取文章链接（如果有的话）
                    article_url = title_elements[i].attr('href') if title_elements[i] else ""
                    if article_url and not article_url.startswith('http'):
                        article_url = f"https://mp.toutiao.com{article_url}"
                    
                    article_data = {
                        'id': i + 1,  # 临时ID
                        'title': title,
                        'views': yueduliang,  # 阅读量
                        'impressions': zhanxian,  # 展现量
                        'likes': dianzan,  # 点赞数
                        'comments': pinglun,  # 评论数
                        'url': article_url,
                        'status': 'published',
                        'published_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                        'source': 'website'  # 标记数据来源
                    }
                    
                    articles_data.append(article_data)
                    
                    self.logger.info(f"✅ 文章 {i+1}: {title[:30]}... - 阅读:{yueduliang}, 展现:{zhanxian}, 点赞:{dianzan}, 评论:{pinglun}")
                    
                except Exception as item_e:
                    self.logger.warning(f"⚠️ 提取第 {i+1} 篇文章数据失败: {str(item_e)}")
                    continue
            
            self.logger.info(f"📊 成功获取 {len(articles_data)} 篇文章的数据")
            return articles_data
            
        except Exception as e:
            self.logger.error(f"❌ 从官网获取文章数据失败: {str(e)}")
            self.logger.error(f"详细错误: {traceback.format_exc()}")
            return []
    
    def _extract_number_from_text(self, text: str) -> int:
        """从文本中提取数字，支持万、千等单位"""
        try:
            if not text or text.strip() == '':
                return 0
            
            # 移除空格和其他字符
            text = text.strip().replace(',', '').replace(' ', '')
            
            # 处理万、千等单位
            if '万' in text:
                number_part = text.replace('万', '')
                try:
                    return int(float(number_part) * 10000)
                except:
                    return 0
            elif '千' in text:
                number_part = text.replace('千', '')
                try:
                    return int(float(number_part) * 1000)
                except:
                    return 0
            else:
                # 提取纯数字
                import re
                numbers = re.findall(r'\d+', text)
                if numbers:
                    return int(numbers[0])
                else:
                    return 0
                    
        except Exception as e:
            self.logger.warning(f"⚠️ 数字提取失败: {text} -> {str(e)}")
            return 0